package git.soulbgm.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.DynamicTableNameInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import git.soulbgm.common.enums.DynamicTableName;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * MybatisPlus 配置
 *
 * @author SoulBGM
 * @date 2022/05/06 23:03
 */
@Configuration
public class MybatisPlusConfig {

    /**
     * MybatisPlus 拦截器
     *
     * @return {@link MybatisPlusInterceptor}
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        DynamicTableNameInnerInterceptor dynamicTableNameInnerInterceptor = new DynamicTableNameInnerInterceptor();
        dynamicTableNameInnerInterceptor.setTableNameHandler((sql, tableName) -> {
            String newTableName = DynamicTableName.INSTANCE.getTableName();
            return newTableName != null ? newTableName : tableName;
        });
        interceptor.addInnerInterceptor(dynamicTableNameInnerInterceptor);
        // 设置分页插件
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

    /*
        例子：
        // 查询
        DynamicTableName.INSTANCE.setTableName(tableName);
        try {
            return mapper.selectList(null);
        } finally {
            DynamicTableName.INSTANCE.remove();
        }

        // 添加
        DynamicTableName.INSTANCE.setTableName(info.getTableName());
        try {
            return mapper.insert(info);
        } finally {
            DynamicTableName.INSTANCE.remove();
        }
     */

}
